package top.cardone.context.util;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.Resource;
import top.cardone.cache.Cache;
import top.cardone.context.ApplicationContextHolder;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/20.
 */
@Log4j2
public class TableUtils {
	public static <R, C, V> Table<R, C, V> newTable(Resource resource) {
		if (!resource.exists()) {
			return HashBasedTable.create();
		}

		try {
			String json = FileUtils.readFileToString(resource.getFile());

			Map<R, Map<C, V>> tableMap = ApplicationContextHolder.getBean(Gson.class).fromJson(json, new TypeToken<Map<R, Map<C, V>>>() {
			}.getType());

			Table<R, C, V> table = HashBasedTable.create();

			if (tableMap.isEmpty()) {
				return table;
			}

			for (Map.Entry<R, Map<C, V>> rowMapEntry : tableMap.entrySet()) {
				if (MapUtils.isEmpty(rowMapEntry.getValue())) {
					continue;
				}

				for (Map.Entry<C, V> colMapEntry : rowMapEntry.getValue().entrySet()) {
					table.put(rowMapEntry.getKey(), colMapEntry.getKey(), colMapEntry.getValue());
				}
			}

			return table;
		} catch (IOException e) {
			log.error(e);

			return HashBasedTable.create();
		}
	}

	public static <R, C, V> Table<R, C, V> newTable(String resourcePath, boolean cache) {
		if (cache) {
			return ApplicationContextHolder.getBean(Cache.class).get("table", resourcePath, () -> {
				Resource resource = ApplicationContextHolder.getApplicationContext().getResource(resourcePath);

				return newTable(resource);
			});
		}

		Resource resource = ApplicationContextHolder.getApplicationContext().getResource(resourcePath);

		return newTable(resource);
	}

	public static <R, C, V> Table<R, C, V> newTable(String resourcePath) {
		return newTable(resourcePath, true);
	}
}